package com.andy.web.dao;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class ShardingDataSourceRouter implements ApplicationContextAware{

	private ApplicationContext applicationContext;
	
	@Resource(name="dataSourceConfig")
	private DataSourceConfig dataSourceConfig;
	
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext = applicationContext;
	}
	
	public void doRoute(String shardingTable, Object param) {
		int dsIndex = 0;
		List<String> dataSourceKeys = dataSourceConfig.getDataSourceKeys();
		String [] beanNames = applicationContext.getBeanNamesForType(ShardingDataSourceRule.class);
		for (String bean : beanNames) {
			ShardingDataSourceRule sdsr = applicationContext.getBean(bean,ShardingDataSourceRule.class);
			if(shardingTable.equalsIgnoreCase(sdsr.getTableName())) {
				dsIndex = sdsr.doSharding(param, dataSourceKeys.size());
				break;
			}
		}
		
		String dsKey = dataSourceConfig.getDataSourceKeys().get(dsIndex);
		
		ShardingContextHolder.setDataSource(dsKey);
	}

}
